package com.uy.cuantoconocesdeuruguay;

import java.util.Random;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.dialogs.EnlargeImageDialogUtils;
import com.uy.cuantoconocesdeuruguay.dialogs.ErrorOccurredDialogUtils;
import com.uy.cuantoconocesdeuruguay.dialogs.QuestionDialogUtils;
import com.uy.cuantoconocesdeuruguay.exceptions.ConnectivityException;
import com.uy.cuantoconocesdeuruguay.server.ServerConnector;
import com.uy.cuantoconocesdeuruguay.utiles.SoundsUtils;
import com.uy.cuantoconocesdeuruguay.utiles.StringPool;
import com.uy.cuantoconocesdeuruguay.utiles.SystemConstants;

@SuppressLint("NewApi")
public class SinglePlayerImage extends ImageBaseActivity {
	@Override 
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image);
		if (savedInstanceState != null) {
			return;
		}
		boolean isTablet = getResources().getBoolean(R.bool.isTablet);
		if (isTablet){
			View layout_main_view = findViewById(R.id.layout_friend_view);
			layout_main_view.setBackgroundResource(R.drawable.friends_bg_tablets);
		}
		MAX_TIME = SystemConstants.SINGLE_PLAYER_MAX_GAME_TIME;
		finishedLoading = false;
		View loaderView = getLayoutInflater().inflate(R.layout.single_player_loader_layout, null);
		AlertDialog.Builder loader = new AlertDialog.Builder(this);
		loader.setView(loaderView);
		loader.setCancelable(true);
	    final Dialog loaderDialog = loader.create();
	    loaderDialog.show();
	    loaderDialog.setOnDismissListener(new OnDismissListener() {			
			@Override
			public void onDismiss(DialogInterface dialog) {
				if (!finishedLoading){
					startActivity(new Intent(getApplicationContext(),MainActivity.class));
					finish();
				}
			}
		});
		word = StringPool.ALL_LETTERS;
		initBoard();
		AsyncTask<Void, Void, Boolean> background = new AsyncTask<Void, Void, Boolean>(){
			@Override
			protected Boolean doInBackground(Void... arg0) {
				try {
//					System.err.println("Started envelope fetcher thread...");
					envelope = ServerConnector.getNextImage(getIntent().getStringExtra(SinglePlayerImage.LAST_IMAGE_ID));
					return envelope != null;
				} catch (ConnectivityException e) {
					e.printStackTrace();
					GoogleAnalyticsTracker.trackException(SinglePlayerImage.this, e);
				}
				return false;
			}
			@Override
			protected void onPostExecute(Boolean success) {
//				System.err.println("Finished envelope fetcher thread...");
				if (success){ 
					MAX_TIME = Math.min(MAX_TIME,MAX_TIME - (int)(SystemConstants.getTime() - envelope.getAssignedTime()));
					try {
						postCreate();
					} catch (Exception e) {
						e.printStackTrace();
						Exception ex = new Exception(StringPool.EXC_ENVELOPE_NULL);
						ErrorOccurredDialogUtils errorDialog = new ErrorOccurredDialogUtils(SinglePlayerImage.this, ex);
						errorDialog.createErrorOccurredPopup();
//						finish();
					}
					loaderDialog.dismiss();
				}else{
					ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(SinglePlayerImage.this, null);
					dialog.createErrorOccurredPopup();
				}
			}
		}; 
		if (android.os.Build.VERSION.SDK_INT > 10) {
			background.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			background.execute();
		}
        finishedLoading = true;
	}
	protected synchronized void checkWord() {
		String writtenWord = StringPool.BLANK; 
		for (int id : fields_ids){
			TextView letterField = (TextView)findViewById(id);
			writtenWord += letterField.getText().toString();
		} 
		if (writtenWord.length() < trimmedWord.length()){
			return;
		}
		if (soundPlayed){ 
			return;
		}
		if (writtenWord.equalsIgnoreCase(trimmedWord)){
			stopTimer();
			try {
				ServerConnector.incrementScore(pictureScore,envelope.getImageID(),true);
			} catch (ConnectivityException e) {
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(SinglePlayerImage.this,e);
				dialog.createErrorOccurredPopup();
				e.printStackTrace();
				return;
			}	
			soundPlayed = true;
			SoundsUtils.playSound(getApplicationContext(), R.raw.correct);
			Toast.makeText(this, getString(R.string.correct), Toast.LENGTH_SHORT).show();
			MainActivity.userData.setLastTimeSkipQuestion(0);		
			QuestionDialogUtils dialog = new QuestionDialogUtils(this);
			dialog.createQuestionsPopup(envelope);
		}else{
			soundPlayed = true;
			SoundsUtils.playSound(getApplicationContext(), R.raw.incorrect);
			Toast.makeText(this, getString(R.string.incorrect), Toast.LENGTH_SHORT).show();
		}
	}

	public void showHint(View view){
		//PREVENT USER TO CLICK MULTIPLE TIMES QUICKLY
		if (SystemConstants.getTime() - hintClickTime < 1000){
			return;
		}
		hintClickTime = SystemConstants.getTime();
		delete(null);  //Remove all letters
		String[] hintIndexes = envelope.getHintIndexes().split(StringPool.COMMA);
		for (int i=0 ; i<hintIndexes.length ; ++i){
			int index = Integer.valueOf(hintIndexes[i]);
			TextView letterField = (TextView)findViewById(fields_ids[index]);
			String letter = String.valueOf(trimmedWord.charAt(index));
			letterField.setText(letter);
			for (int idBox : boxes_ids){
				TextView letterBox = (TextView)findViewById(idBox);
				if (letterBox.getText().toString().equals(letter)){
					LinearLayout fieldHolder = (LinearLayout)letterField.getParent();
					animateShowingField(letterField);
					if (!lettersHistory.contains(fieldHolder)){
						lettersHistory.add(fieldHolder);
					}
					letterBox.setText(StringPool.BLANK);
					break;
				}
			}
		}
		if (hintUsed){
			return;
		}
		hintUsed = true;
		if (!envelope.isHintUsed()){
			try {
				long timeRemaining = MAX_TIME - timeElapsed;
				long timeIncremented = timeRemaining/2;
				timeElapsed = (int) (timeElapsed + timeIncremented);
				ServerConnector.useHint(envelope.getImageID(),timeIncremented);
				envelope.setHintUsed(true);
			} catch (ConnectivityException e) {
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(this,e);
				dialog.createErrorOccurredPopup();
				e.printStackTrace();
			}
		}
	}
	
	public void bomb(View view){
		int cantLetrasRemover = (int) Math.ceil( ((float)removableBoxes.size())*0.6f );
		if (cantLetrasRemover == 0){
			return;
		}
		if (bombUsed){ 
			Toast.makeText(this, getString(R.string.single_player_image_bomb_used), Toast.LENGTH_SHORT).show();
			return;
		}
		soundPlayed = false;
		bombUsed = true;
		Random rand = new Random(SystemConstants.getTime());
		for (int i=0 ; i<cantLetrasRemover ; ++i){
			TextView box = removableBoxes.remove(rand.nextInt(removableBoxes.size()));
			box.setText(StringPool.BLANK);
		}
		if (!envelope.isBombUsed()){
			try {
				long timeRemaining = MAX_TIME - timeElapsed;
				long timeIncremented = timeRemaining/2;
				timeElapsed = (int) (timeElapsed + timeIncremented);
				ServerConnector.useBomb(envelope.getImageID(),timeIncremented);
				envelope.setBombUsed(true);
			} catch (ConnectivityException e) {
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(this,e);
				dialog.createErrorOccurredPopup();
				e.printStackTrace();
			}
		}
	}
	
	public void nextQuestion(View view){
		//PREVENT USER TO CLICK MULTIPLE TIMES QUICKLY
		if (SystemConstants.getTime() - lastNextQuestionClickTime < 1000){
			return;
		}
		lastNextQuestionClickTime = SystemConstants.getTime();
		long elapsedTime = (SystemConstants.getTime() - MainActivity.userData.getLastTimeSkipQuestion());
		if (elapsedTime > SystemConstants.MIN_SKIP_DELAY || timeUp || (view == null)){
			stopTimer();
			try {
				ServerConnector.skipImage(envelope.getImageID());
				if (!( timeUp || (view == null) ) ){
					MainActivity.userData.setLastTimeSkipQuestion(SystemConstants.getTime());
				}
				String lastImageID = String.valueOf(envelope.getImageID());
				EnlargeImageDialogUtils.reset();
				SinglePlayerImage.reset();
				if (onForeground){
					Intent i = new Intent(getApplicationContext(), SinglePlayerImage.class);
					if (view != null){//Hizo click en saltar imagen
						i.putExtra(SinglePlayerImage.LAST_IMAGE_ID, lastImageID);
					}
					startActivity(i);
				}
			} catch (ConnectivityException e) {
				ErrorOccurredDialogUtils dialog = new ErrorOccurredDialogUtils(this,e);
				dialog.createErrorOccurredPopup();
				e.printStackTrace();
				return;
			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
			finish();
		}else{
			long remainingTime = (SystemConstants.MIN_SKIP_DELAY - elapsedTime)/1000;
			int minutes = (int) (remainingTime/60);
			int seconds = (int) (remainingTime % 60);
			String mm = minutes < 10 ? StringPool.ZERO+minutes : String.valueOf(minutes);
			String ss = seconds < 10 ? StringPool.ZERO+seconds : String.valueOf(seconds);
			Toast.makeText(this, getString(R.string.single_player_image_skip_in)+mm+StringPool.COLON+ss, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setTitle(getString(R.string.single_player_image_exit_confirm));
	    builder.setCancelable(false);  
	    builder.setPositiveButton(getString(R.string.single_player_image_exit), new DialogInterface.OnClickListener() {
	    	@Override
	    	public void onClick(DialogInterface dialog, int id) {
				goToMenu(false);
	    	} 
	    });	    
	    builder.setNegativeButton(getString(R.string.single_player_image_continue), new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int id) {
	    	} 
	    }); 
	    Dialog enlargedImagePopup = builder.create();
		enlargedImagePopup.show();
	}	
	protected void goToMenu(boolean gameCompleted) {
		stopTimer();
		Intent i = new Intent(getApplicationContext(), MainActivity.class);
		i.putExtra(MainActivity.GAME_COMPLETED, gameCompleted);
		startActivity(i);
		finish();
	}
	@Override
	public void trackScreen() {
		GoogleAnalyticsTracker.trackScreen(this, "Imagen single player");
	}
	private static String LAST_IMAGE_ID = "com.uy.cuantoconocesdeuruguay.Image.LAST_IMAGE_ID";
	private boolean hintUsed = false, bombUsed = false;
	private long hintClickTime;
}
